// 主要JavaScript逻辑

// 检测运行环境
const isDesktopApp = typeof window !== 'undefined' && window.go !== undefined;
const appMode = isDesktopApp ? 'desktop' : 'web';

console.log('应用运行模式:', appMode);

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

// 初始化应用
function initializeApp() {
    console.log('初始化应用, 运行模式:', appMode);
    
    // 检查登录状态
    if (!getToken()) {
        console.log('未找到token，显示登录界面');
        showLoginModal();
        return;
    }
    
    console.log('已登录，token:', getToken().substring(0, 20) + '...');
    
    // 加载数据
    loadDashboardData();
    
    // 设置事件监听
    setupEventListeners();
    
    // 桌面应用特有初始化
    if (isDesktopApp) {
        initDesktopFeatures();
    }
}

// 设置事件监听器
function setupEventListeners() {
    // 模态框外部点击关闭
    window.onclick = function(event) {
        if (event.target.classList.contains('modal')) {
            event.target.style.display = 'none';
        }
    }
    
    // 导入类型切换
    document.addEventListener('change', function(event) {
        if (event.target.name === 'import-type') {
            const fileImport = document.getElementById('file-import');
            const sampleImport = document.getElementById('sample-import');
            
            if (event.target.value === 'file') {
                fileImport.style.display = 'block';
                sampleImport.style.display = 'none';
            } else {
                fileImport.style.display = 'none';
                sampleImport.style.display = 'block';
            }
        }
        
        // 处理互斥复选框
        if (event.target.id === 'skip-exists' && event.target.checked) {
            document.getElementById('update-exists').checked = false;
        }
        if (event.target.id === 'update-exists' && event.target.checked) {
            document.getElementById('skip-exists').checked = false;
        }
    });
}

// 显示页面
function showPage(pageId, clickedElement) {
    // 隐藏所有页面
    const pages = document.querySelectorAll('.page');
    pages.forEach(page => page.classList.remove('active'));
    
    // 显示指定页面
    const targetPage = document.getElementById(pageId);
    if (targetPage) {
        targetPage.classList.add('active');
    }
    
    // 更新导航状态
    const links = document.querySelectorAll('.sidebar-menu a');
    links.forEach(link => link.classList.remove('active'));
    
    // 如果有点击元素，添加active类
    if (clickedElement) {
        clickedElement.classList.add('active');
    } else {
        // 如果没有传入点击元素，查找对应的导航链接
        const targetLink = document.querySelector(`[onclick*="showPage('${pageId}')"]`);
        if (targetLink) {
            targetLink.classList.add('active');
        }
    }
    
    // 更新页面标题
    const titles = {
        'dashboard': '数据仪表板',
        'stocks': '股票管理',
        'pools': '股票池管理',
        'tags': '标签管理',
        'strategies': '策略管理',
        'risk': '风险管理'
    };
    document.getElementById('page-title').textContent = titles[pageId] || '系统管理';
    
    // 加载页面数据
    loadPageData(pageId);
}

// 加载页面数据
async function loadPageData(pageId) {
    try {
        switch(pageId) {
            case 'dashboard':
                await loadDashboardData();
                break;
            case 'stocks':
                await loadStocksData();
                break;
            case 'pools':
                await loadPoolsData();
                break;
            case 'tags':
                await loadTagsData();
                break;
            case 'strategies':
                await loadStrategiesData();
                break;
            case 'risk':
                await loadRiskData();
                break;
        }
    } catch (error) {
        showAlert('加载数据失败: ' + error.message, 'error');
    }
}

// 加载仪表板数据
async function loadDashboardData() {
    try {
        console.log('开始加载仪表板数据...');
        const stats = await getStatistics();
        console.log('仪表板统计数据:', stats);
        
        document.getElementById('total-stocks').textContent = stats.data?.total_stocks || '0';
        document.getElementById('total-pools').textContent = stats.data?.total_pools || '0';
        document.getElementById('total-strategies').textContent = stats.data?.total_strategies || '0';
        document.getElementById('active-strategies').textContent = stats.data?.active_strategies || '0';
        
        console.log('仪表板数据加载完成');
    } catch (error) {
        console.error('加载仪表板数据失败:', error);
        // 设置默认值
        document.getElementById('total-stocks').textContent = '0';
        document.getElementById('total-pools').textContent = '0';
        document.getElementById('total-strategies').textContent = '0';
        document.getElementById('active-strategies').textContent = '0';
    }
}

// 加载股票数据
async function loadStocksData() {
    const content = document.getElementById('stocks-content');
    content.innerHTML = `
        <div class="filters-bar">
            <div class="filter-group">
                <input type="text" id="stock-search" placeholder="搜索股票代码或名称" class="form-control">
                <select id="market-filter" class="form-control">
                    <option value="">所有市场</option>
                    <option value="SH">上海交易所</option>
                    <option value="SZ">深圳交易所</option>
                    <option value="BJ">北京交易所</option>
                </select>
                <select id="industry-filter" class="form-control">
                    <option value="">所有行业</option>
                </select>
                <select id="status-filter" class="form-control">
                    <option value="">所有状态</option>
                    <option value="true">有效</option>
                    <option value="false">无效</option>
                </select>
                <button class="btn btn-primary" onclick="searchStocks()">搜索</button>
                <button class="btn btn-secondary" onclick="resetFilters()">重置</button>
                <button class="btn btn-info" onclick="toggleAdvancedFilters()">高级筛选</button>
            </div>
            <div id="advanced-filters" class="filter-group" style="display: none; margin-top: 12px; padding-top: 12px; border-top: 1px solid #e8e8e8;">
                <input type="number" id="min-market-cap" placeholder="最小市值(亿)" class="form-control">
                <input type="number" id="max-market-cap" placeholder="最大市值(亿)" class="form-control">
                <input type="number" id="min-pe-ratio" placeholder="最小市盈率" class="form-control" step="0.1">
                <input type="number" id="max-pe-ratio" placeholder="最大市盈率" class="form-control" step="0.1">
                <select id="sort-by" class="form-control">
                    <option value="market_cap">按市值排序</option>
                    <option value="pe_ratio">按市盈率排序</option>
                    <option value="pb_ratio">按市净率排序</option>
                    <option value="code">按代码排序</option>
                    <option value="name">按名称排序</option>
                </select>
                <select id="sort-order" class="form-control">
                    <option value="desc">降序</option>
                    <option value="asc">升序</option>
                </select>
            </div>
        </div>
        <div class="loading"><div class="spinner"></div><p>正在加载股票数据...</p></div>
    `;
    
    try {
        // 加载行业列表
        try {
            console.log('开始加载行业列表...');
            const industries = await getIndustries();
            console.log('行业数据响应:', industries);
            
            const industrySelect = document.getElementById('industry-filter');
            if (industries && industries.data && Array.isArray(industries.data)) {
                console.log('找到行业数据，数量:', industries.data.length);
                industries.data.forEach(industry => {
                    const option = document.createElement('option');
                    option.value = industry;
                    option.textContent = industry;
                    industrySelect.appendChild(option);
                });
            } else {
                console.warn('行业数据格式不正确或为空:', industries);
                // 如果没有行业数据，添加一个默认选项
                const option = document.createElement('option');
                option.value = '';
                option.textContent = '暂无行业数据';
                industrySelect.appendChild(option);
            }
        } catch (industryError) {
            console.error('加载行业列表失败:', industryError);
            // 行业列表加载失败不影响主要功能，添加默认选项
            const industrySelect = document.getElementById('industry-filter');
            const option = document.createElement('option');
            option.value = '';
            option.textContent = '加载失败';
            industrySelect.appendChild(option);
        }
        
        // 加载股票数据
        await loadStocksList();
    } catch (error) {
        console.error('加载股票数据失败:', error);
        content.innerHTML = `<div class="alert alert-error">加载失败: ${error.message || '未知错误'}</div>`;
    }
}

// 生成分页组件
function generatePagination(currentPage, pageSize, total, params = {}) {
    if (total <= 0) {
        return ''; // 如果没有数据，不显示分页
    }
    
    const totalPages = Math.ceil(total / pageSize);
    const prevPage = Math.max(1, currentPage - 1);
    const nextPage = Math.min(totalPages, currentPage + 1);
    
    // 计算显示的页码范围
    let startPage = Math.max(1, currentPage - 2);
    let endPage = Math.min(totalPages, currentPage + 2);
    
    // 调整范围保证显示5个页码
    if (endPage - startPage < 4) {
        if (startPage === 1) {
            endPage = Math.min(totalPages, startPage + 4);
        } else if (endPage === totalPages) {
            startPage = Math.max(1, endPage - 4);
        }
    }
    
    // 移除page和limit参数，由函数传入
    const baseParams = Object.assign({}, params);
    delete baseParams.page;
    delete baseParams.limit;
    
    // 为分页按钮生成点击事件
    const createClickHandler = (page, limit) => {
        const params = Object.assign({}, baseParams, {page: page, limit: limit});
        return `loadStocksList(${JSON.stringify(params)})`;
    };
    
    let paginationHTML = `
        <div class="pagination-container">
            <div class="pagination-info">
                <span>显示 ${((currentPage - 1) * pageSize) + 1} - ${Math.min(currentPage * pageSize, total)} 条，共 ${total} 条记录</span>
                <div class="page-size-selector">
                    <label>每页显示：</label>
                    <select onchange="changePageSize(this.value, ${JSON.stringify(baseParams)})">
                        <option value="10" ${pageSize == 10 ? 'selected' : ''}>10</option>
                        <option value="20" ${pageSize == 20 ? 'selected' : ''}>20</option>
                        <option value="50" ${pageSize == 50 ? 'selected' : ''}>50</option>
                        <option value="100" ${pageSize == 100 ? 'selected' : ''}>100</option>
                    </select>
                    <span>条</span>
                </div>
            </div>`;
    
    // 只有在多于一页时才显示分页按钮
    if (totalPages > 1) {
        paginationHTML += `
            <div class="pagination">
                <button class="btn pagination-btn" ${currentPage <= 1 ? 'disabled' : ''} 
                    onclick="${createClickHandler(1, pageSize)}">
                    <i class="fas fa-angle-double-left"></i> 首页
                </button>
                <button class="btn pagination-btn" ${currentPage <= 1 ? 'disabled' : ''} 
                    onclick="${createClickHandler(prevPage, pageSize)}">
                    <i class="fas fa-angle-left"></i> 上一页
                </button>`;
        
        // 添加页码按钮
        if (startPage > 1) {
            paginationHTML += `<button class="btn pagination-number" onclick="${createClickHandler(1, pageSize)}">1</button>`;
            if (startPage > 2) {
                paginationHTML += `<span class="pagination-ellipsis">...</span>`;
            }
        }
        
        for (let i = startPage; i <= endPage; i++) {
            paginationHTML += `
                <button class="btn pagination-number ${i === currentPage ? 'active' : ''}" 
                    onclick="${createClickHandler(i, pageSize)}">
                    ${i}
                </button>
            `;
        }
        
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                paginationHTML += `<span class="pagination-ellipsis">...</span>`;
            }
            paginationHTML += `<button class="btn pagination-number" onclick="${createClickHandler(totalPages, pageSize)}">${totalPages}</button>`;
        }
        
        paginationHTML += `
                <button class="btn pagination-btn" ${currentPage >= totalPages ? 'disabled' : ''} 
                    onclick="${createClickHandler(nextPage, pageSize)}">
                    下一页 <i class="fas fa-angle-right"></i>
                </button>
                <button class="btn pagination-btn" ${currentPage >= totalPages ? 'disabled' : ''} 
                    onclick="${createClickHandler(totalPages, pageSize)}">
                    末页 <i class="fas fa-angle-double-right"></i>
                </button>
            </div>
            <div class="page-jumper">
                <span>跳转到：</span>
                <input type="number" id="page-jump-input" min="1" max="${totalPages}" placeholder="${currentPage}" 
                    onkeypress="if(event.key==='Enter') jumpToPage(${JSON.stringify(baseParams)}, ${pageSize})">
                <button class="btn btn-sm" onclick="jumpToPage(${JSON.stringify(baseParams)}, ${pageSize})">跳转</button>
            </div>`;
    } else {
        // 只有一页时，显示简化的分页信息
        paginationHTML += `
            <div class="pagination">
                <span class="pagination-single-page">共 1 页</span>
            </div>`;
    }
        
    
    return paginationHTML;
}

// 改变每页显示数量
function changePageSize(newPageSize, params) {
    const newParams = Object.assign({}, params, {page: 1, limit: parseInt(newPageSize)});
    loadStocksList(newParams);
}

// 跳转到指定页面
function jumpToPage(params, pageSize) {
    const input = document.getElementById('page-jump-input');
    const page = parseInt(input.value);
    
    if (isNaN(page) || page < 1) {
        showAlert('请输入有效的页码', 'error');
        return;
    }
    
    const newParams = Object.assign({}, params, {page: page, limit: pageSize});
    loadStocksList(newParams);
}

// 加载股票列表
async function loadStocksList(params = {}) {
    const stocksTable = document.querySelector('#stocks-content .table-container') || 
        document.createElement('div');
    stocksTable.className = 'table-container';
    
    try {
        console.log('开始加载股票列表...', params);
        
        const defaultParams = {
            page: 1,
            limit: 5,  // 为了测试分页功能，暂时设置为5条
            sort_by: 'market_cap',
            sort_order: 'desc'
        };
        
        const finalParams = Object.assign({}, defaultParams, params);
        const result = await getStocks(finalParams);
        console.log('股票数据响应:', result);
        
        const stocks = result.data?.list || [];
        const total = result.data?.total || 0;
        const currentPage = finalParams.page;
        const pageSize = finalParams.limit;
        
        console.log(`加载了 ${stocks.length} 支股票，总数 ${total}`);
        
        stocksTable.innerHTML = `
            <div class="table-header">
                <h4>股票列表 (共 ${total} 支)</h4>
                <div class="table-actions">
                    <button class="btn btn-success" onclick="openModal('importModal')">
                        <i class="fas fa-upload"></i> 导入股票
                    </button>
                    <button class="btn btn-info" onclick="exportStocks()">
                        <i class="fas fa-download"></i> 导出数据
                    </button>
                    <button class="btn btn-warning" onclick="syncMarketDataAction()">
                        <i class="fas fa-sync"></i> 同步数据
                    </button>
                </div>
            </div>
            <table class="table">
                <thead>
                    <tr>
                        <th><input type="checkbox" id="select-all" onchange="toggleSelectAll()"></th>
                        <th>股票代码</th>
                        <th>股票名称</th>
                        <th>市场</th>
                        <th>行业</th>
                        <th>市值(亿)</th>
                        <th>市盈率</th>
                        <th>市净率</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    ${stocks.map(stock => `
                        <tr>
                            <td><input type="checkbox" class="stock-checkbox" value="${stock.code}"></td>
                            <td><strong>${stock.code}</strong></td>
                            <td>${stock.name}</td>
                            <td>${stock.market}</td>
                            <td>${stock.industry || '-'}</td>
                            <td>${stock.market_cap ? (stock.market_cap / 100000000).toFixed(0) : '-'}</td>
                            <td>${stock.pe_ratio || '-'}</td>
                            <td>${stock.pb_ratio || '-'}</td>
                            <td><span class="tag ${stock.is_active ? 'tag-success' : 'tag-warning'}">${stock.is_active ? '有效' : '无效'}</span></td>
                            <td>
                                <button class="btn btn-sm btn-primary" onclick="editStock(${stock.id})">编辑</button>
                                <button class="btn btn-sm btn-danger" onclick="deleteStockData(${stock.id}, '${stock.name}')">删除</button>
                            </td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
            ${generatePagination(currentPage, pageSize, total, finalParams)}
            <div class="bulk-actions">
                <button class="btn btn-warning" onclick="bulkUpdateStatus(true)">批量启用</button>
                <button class="btn btn-secondary" onclick="bulkUpdateStatus(false)">批量禁用</button>
                <button class="btn btn-danger" onclick="bulkDeleteStocks()">批量删除</button>
            </div>
        `;
        
        // 更新内容
        const existingTable = document.querySelector('#stocks-content .table-container');
        if (existingTable) {
            existingTable.replaceWith(stocksTable);
        } else {
            const loadingDiv = document.querySelector('#stocks-content .loading');
            if (loadingDiv) {
                loadingDiv.replaceWith(stocksTable);
            } else {
                document.getElementById('stocks-content').appendChild(stocksTable);
            }
        }
        
        console.log('股票列表加载完成');
        
    } catch (error) {
        console.error('加载股票列表失败:', error);
        stocksTable.innerHTML = `<div class="alert alert-error">加载失败: ${error.message || '未知错误'}</div>`;
    }
}

// 加载股票池数据
async function loadPoolsData() {
    const content = document.getElementById('pools-content');
    content.innerHTML = '<div class="loading"><div class="spinner"></div><p>正在加载股票池数据...</p></div>';
    
    try {
        const result = await getPools();
        const pools = result.data?.list || [];
        
        content.innerHTML = `
            <table class="table">
                <thead>
                    <tr>
                        <th>股票池名称</th>
                        <th>类型</th>
                        <th>股票数量</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    ${pools.map(pool => `
                        <tr>
                            <td>${pool.name}</td>
                            <td>${pool.type === 'static' ? '静态' : '动态'}</td>
                            <td>-</td>
                            <td><span class="tag tag-success">正常</span></td>
                            <td>
                                <button class="btn btn-primary" onclick="editPool(${pool.id})">编辑</button>
                                <button class="btn btn-danger" onclick="deletePool(${pool.id})">删除</button>
                            </td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        `;
    } catch (error) {
        content.innerHTML = `<div class="alert alert-error">加载失败: ${error.message}</div>`;
    }
}

// 加载标签数据
async function loadTagsData() {
    const content = document.getElementById('tags-content');
    content.innerHTML = '<div class="loading"><div class="spinner"></div><p>正在加载标签数据...</p></div>';
    
    try {
        const result = await getTags();
        const tags = result.data?.list || [];
        
        content.innerHTML = `
            <table class="table">
                <thead>
                    <tr>
                        <th>标签名称</th>
                        <th>分类</th>
                        <th>颜色</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    ${tags.map(tag => `
                        <tr>
                            <td>${tag.name}</td>
                            <td>${tag.category}</td>
                            <td><span style="color: ${tag.color}">●</span> ${tag.color}</td>
                            <td><span class="tag tag-success">正常</span></td>
                            <td>
                                <button class="btn btn-primary" onclick="editTag(${tag.id})">编辑</button>
                                <button class="btn btn-danger" onclick="deleteTag(${tag.id})">删除</button>
                            </td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        `;
    } catch (error) {
        content.innerHTML = `<div class="alert alert-error">加载失败: ${error.message}</div>`;
    }
}

// 加载策略数据
async function loadStrategiesData() {
    const content = document.getElementById('strategies-content');
    content.innerHTML = '<div class="loading"><div class="spinner"></div><p>正在加载策略数据...</p></div>';
    
    try {
        const result = await getStrategies();
        const strategies = result.data?.list || [];
        
        content.innerHTML = `
            <table class="table">
                <thead>
                    <tr>
                        <th>策略名称</th>
                        <th>策略类型</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    ${strategies.map(strategy => `
                        <tr>
                            <td>${strategy.name}</td>
                            <td>${strategy.type}</td>
                            <td><span class="tag ${strategy.is_active ? 'tag-success' : 'tag-warning'}">${strategy.is_active ? '运行中' : '已停止'}</span></td>
                            <td>
                                ${strategy.is_active 
                                    ? `<button class="btn btn-warning" onclick="stopStrategy(${strategy.id})">停止</button>`
                                    : `<button class="btn btn-success" onclick="startStrategy(${strategy.id})">启动</button>`
                                }
                                <button class="btn btn-primary" onclick="editStrategy(${strategy.id})">编辑</button>
                                <button class="btn btn-danger" onclick="deleteStrategy(${strategy.id})">删除</button>
                            </td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        `;
    } catch (error) {
        content.innerHTML = `<div class="alert alert-error">加载失败: ${error.message}</div>`;
    }
}

// 加载风险数据
async function loadRiskData() {
    // 风险管理页面的数据加载
    console.log('加载风险管理数据');
}

// 打开模态框
function openModal(modalId) {
    createModal(modalId);
}

// 关闭模态框
function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.style.display = 'none';
    }
}

// 创建模态框
function createModal(modalId) {
    const modalsContainer = document.getElementById('modals');
    
    let modalContent = '';
    
    switch(modalId) {
        case 'stockModal':
            modalContent = createStockModal();
            break;
        case 'importModal':
            modalContent = createImportModal();
            break;
        case 'poolModal':
            modalContent = createPoolModal();
            break;
        case 'tagModal':
            modalContent = createTagModal();
            break;
        case 'strategyModal':
            modalContent = createStrategyModal();
            break;
    }
    
    modalsContainer.innerHTML = modalContent;
    document.getElementById(modalId).style.display = 'block';
}

// 创建股票导入模态框
function createImportModal() {
    return `
        <div id="importModal" class="modal">
            <div class="modal-content">
                <div class="modal-header">
                    <h3>导入股票数据</h3>
                    <button class="close" onclick="closeModal('importModal')">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>选择导入方式</label>
                        <div class="radio-group">
                            <label><input type="radio" name="import-type" value="file" checked> 文件导入</label>
                            <label><input type="radio" name="import-type" value="sample"> 导入示例数据</label>
                        </div>
                    </div>
                    
                    <div id="file-import" class="import-section">
                        <div class="form-group">
                            <label>选择CSV文件</label>
                            <input type="file" id="import-file" accept=".csv" class="form-control">
                            <small class="form-text">支持CSV格式，列顺序：股票代码,股票名称,市场,行业,板块,市值,市盈率,市净率</small>
                        </div>
                        <div class="form-group">
                            <label>导入选项</label>
                            <div class="checkbox-group">
                                <label><input type="checkbox" id="skip-exists" checked> 跳过已存在的股票</label>
                                <label><input type="checkbox" id="update-exists"> 更新已存在的股票</label>
                            </div>
                        </div>
                    </div>
                    
                    <div id="sample-import" class="import-section" style="display: none;">
                        <p>将导入预设的示例股票数据，包含主要的蓝筹股和热门股票。</p>
                    </div>
                    
                    <div class="form-group">
                        <button type="button" class="btn btn-primary" onclick="performImport()">开始导入</button>
                        <button type="button" class="btn" onclick="closeModal('importModal')">取消</button>
                    </div>
                    
                    <div id="import-progress" style="display: none;">
                        <div class="progress">
                            <div class="progress-bar" id="progress-bar"></div>
                        </div>
                        <div id="import-status">导入中...</div>
                    </div>
                    
                    <div id="import-result" style="display: none;">
                        <h4>导入结果</h4>
                        <div id="import-summary"></div>
                        <div id="import-errors"></div>
                    </div>
                </div>
            </div>
        </div>
    `;
}

// 创建股票模态框
function createStockModal() {
    return `
        <div id="stockModal" class="modal">
            <div class="modal-content">
                <div class="modal-header">
                    <h3>添加股票</h3>
                    <button class="close" onclick="closeModal('stockModal')">&times;</button>
                </div>
                <form id="stock-form">
                    <div class="form-group">
                        <label>股票代码</label>
                        <input type="text" class="form-control" name="code" placeholder="请输入6位股票代码" required>
                    </div>
                    <div class="form-group">
                        <label>股票名称</label>
                        <input type="text" class="form-control" name="name" placeholder="请输入股票名称" required>
                    </div>
                    <div class="form-group">
                        <label>市场</label>
                        <select class="form-control" name="market" required>
                            <option value="">请选择市场</option>
                            <option value="SH">上海交易所</option>
                            <option value="SZ">深圳交易所</option>
                            <option value="BJ">北京交易所</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>行业</label>
                        <input type="text" class="form-control" name="industry" placeholder="请输入行业">
                    </div>
                    <div class="form-group">
                        <button type="button" class="btn btn-primary" onclick="submitStock()">保存</button>
                        <button type="button" class="btn" onclick="closeModal('stockModal')">取消</button>
                    </div>
                </form>
            </div>
        </div>
    `;
}

// 创建股票池模态框
function createPoolModal() {
    return `
        <div id="poolModal" class="modal">
            <div class="modal-content">
                <div class="modal-header">
                    <h3>创建股票池</h3>
                    <button class="close" onclick="closeModal('poolModal')">&times;</button>
                </div>
                <form id="pool-form">
                    <div class="form-group">
                        <label>股票池名称</label>
                        <input type="text" class="form-control" name="name" placeholder="请输入股票池名称" required>
                    </div>
                    <div class="form-group">
                        <label>类型</label>
                        <select class="form-control" name="type" required>
                            <option value="">请选择类型</option>
                            <option value="static">静态股票池</option>
                            <option value="dynamic">动态股票池</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>描述</label>
                        <textarea class="form-control" name="description" rows="3" placeholder="请输入股票池描述"></textarea>
                    </div>
                    <div class="form-group">
                        <label>最大股票数量</label>
                        <input type="number" class="form-control" name="max_size" value="100" min="1" max="1000">
                    </div>
                    <div class="form-group">
                        <button type="button" class="btn btn-primary" onclick="submitPool()">保存</button>
                        <button type="button" class="btn" onclick="closeModal('poolModal')">取消</button>
                    </div>
                </form>
            </div>
        </div>
    `;
}

// 创建标签模态框
function createTagModal() {
    return `
        <div id="tagModal" class="modal">
            <div class="modal-content">
                <div class="modal-header">
                    <h3>创建标签</h3>
                    <button class="close" onclick="closeModal('tagModal')">&times;</button>
                </div>
                <form id="tag-form">
                    <div class="form-group">
                        <label>标签名称</label>
                        <input type="text" class="form-control" name="name" placeholder="请输入标签名称" required>
                    </div>
                    <div class="form-group">
                        <label>分类</label>
                        <select class="form-control" name="category" required>
                            <option value="">请选择分类</option>
                            <option value="industry">行业</option>
                            <option value="concept">概念</option>
                            <option value="risk">风险</option>
                            <option value="market_cap">市值</option>
                            <option value="custom">自定义</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>颜色</label>
                        <input type="color" class="form-control" name="color" value="#1890ff">
                    </div>
                    <div class="form-group">
                        <label>描述</label>
                        <textarea class="form-control" name="description" rows="3" placeholder="请输入标签描述"></textarea>
                    </div>
                    <div class="form-group">
                        <button type="button" class="btn btn-primary" onclick="submitTag()">保存</button>
                        <button type="button" class="btn" onclick="closeModal('tagModal')">取消</button>
                    </div>
                </form>
            </div>
        </div>
    `;
}

// 创建策略模态框
function createStrategyModal() {
    return `
        <div id="strategyModal" class="modal">
            <div class="modal-content">
                <div class="modal-header">
                    <h3>创建策略</h3>
                    <button class="close" onclick="closeModal('strategyModal')">&times;</button>
                </div>
                <form id="strategy-form">
                    <div class="form-group">
                        <label>策略名称</label>
                        <input type="text" class="form-control" name="name" placeholder="请输入策略名称" required>
                    </div>
                    <div class="form-group">
                        <label>策略类型</label>
                        <select class="form-control" name="type" required>
                            <option value="">请选择策略类型</option>
                            <option value="ma">移动平均线策略</option>
                            <option value="bollinger">布林带策略</option>
                            <option value="rsi">RSI策略</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>描述</label>
                        <textarea class="form-control" name="description" rows="3" placeholder="请输入策略描述"></textarea>
                    </div>
                    <div class="form-group">
                        <button type="button" class="btn btn-primary" onclick="submitStrategy()">保存</button>
                        <button type="button" class="btn" onclick="closeModal('strategyModal')">取消</button>
                    </div>
                </form>
            </div>
        </div>
    `;
}

// 提交股票
async function submitStock() {
    const form = document.getElementById('stock-form');
    const formData = new FormData(form);
    const stockData = Object.fromEntries(formData);
    
    // 添加调试日志
    console.log('提交股票数据:', stockData);
    console.log('表单元素:', form);
    console.log('FormData内容:', Array.from(formData.entries()));
    
    // 验证必填字段
    if (!stockData.code || !stockData.name || !stockData.market) {
        showAlert('请填写所有必填字段（股票代码、股票名称、市场）', 'error');
        return;
    }
    
    try {
        console.log('调用createStock API...');
        const result = await createStock(stockData);
        console.log('createStock API返回结果:', result);
        closeModal('stockModal');
        showAlert('股票添加成功', 'success');
        loadStocksData();
    } catch (error) {
        console.error('提交股票失败:', error);
        showAlert('添加失败: ' + error.message, 'error');
    }
}

// 提交股票池
async function submitPool() {
    const form = document.getElementById('pool-form');
    const formData = new FormData(form);
    const poolData = Object.fromEntries(formData);
    
    try {
        await createPool(poolData);
        closeModal('poolModal');
        showAlert('股票池创建成功', 'success');
        loadPoolsData();
    } catch (error) {
        showAlert('创建失败: ' + error.message, 'error');
    }
}

// 提交标签
async function submitTag() {
    const form = document.getElementById('tag-form');
    const formData = new FormData(form);
    const tagData = Object.fromEntries(formData);
    
    try {
        await createTag(tagData);
        closeModal('tagModal');
        showAlert('标签创建成功', 'success');
        loadTagsData();
    } catch (error) {
        showAlert('创建失败: ' + error.message, 'error');
    }
}

// 提交策略
async function submitStrategy() {
    const form = document.getElementById('strategy-form');
    const formData = new FormData(form);
    const strategyData = Object.fromEntries(formData);
    strategyData.parameters = {};
    
    try {
        await createStrategy(strategyData);
        closeModal('strategyModal');
        showAlert('策略创建成功', 'success');
        loadStrategiesData();
    } catch (error) {
        showAlert('创建失败: ' + error.message, 'error');
    }
}

// 显示登录模态框
function showLoginModal() {
    const modalsContainer = document.getElementById('modals');
    modalsContainer.innerHTML = `
        <div id="loginModal" class="modal" style="display: block;">
            <div class="modal-content">
                <div class="modal-header">
                    <h3>用户登录</h3>
                </div>
                <form id="login-form">
                    <div class="form-group">
                        <label>用户名</label>
                        <input type="text" class="form-control" name="username" value="admin" required>
                    </div>
                    <div class="form-group">
                        <label>密码</label>
                        <input type="password" class="form-control" name="password" value="admin123" required>
                    </div>
                    <div class="form-group">
                        <button type="button" class="btn btn-primary" onclick="performLogin()">登录</button>
                    </div>
                </form>
            </div>
        </div>
    `;
}

// 执行导入
async function performImport() {
    const importType = document.querySelector('input[name="import-type"]:checked').value;
    const progressDiv = document.getElementById('import-progress');
    const resultDiv = document.getElementById('import-result');
    
    // 显示进度
    progressDiv.style.display = 'block';
    resultDiv.style.display = 'none';
    
    try {
        let importData;
        
        if (importType === 'sample') {
            // 导入示例数据
            importData = {
                stocks: await getSampleStocks(),
                skip_exists: true,
                update_exists: false
            };
        } else {
            // 文件导入
            const fileInput = document.getElementById('import-file');
            if (!fileInput.files.length) {
                showAlert('请选择要导入的文件', 'error');
                progressDiv.style.display = 'none';
                return;
            }
            
            const skipExists = document.getElementById('skip-exists').checked;
            const updateExists = document.getElementById('update-exists').checked;
            
            const csvContent = await readFileAsText(fileInput.files[0]);
            const stocks = parseCsvContent(csvContent);
            
            importData = {
                stocks: stocks,
                skip_exists: skipExists,
                update_exists: updateExists
            };
        }
        
        // 更新进度
        document.getElementById('progress-bar').style.width = '50%';
        document.getElementById('import-status').textContent = '正在处理数据...';
        
        // 执行导入
        const result = await importStocks(importData);
        
        // 完成进度
        document.getElementById('progress-bar').style.width = '100%';
        document.getElementById('import-status').textContent = '导入完成';
        
        // 显示结果
        setTimeout(() => {
            progressDiv.style.display = 'none';
            showImportResult(result.data);
        }, 1000);
        
    } catch (error) {
        progressDiv.style.display = 'none';
        showAlert('导入失败: ' + error.message, 'error');
    }
}

// 获取示例数据
function getSampleStocks() {
    return [
        {
            code: "000001",
            name: "平安银行",
            market: "SZ",
            industry: "银行",
            sector: "金融",
            market_cap: 320000000000,
            pe_ratio: 5.2,
            pb_ratio: 0.8
        },
        {
            code: "600519",
            name: "贵州茅台",
            market: "SH",
            industry: "白酒",
            sector: "消费",
            market_cap: 2200000000000,
            pe_ratio: 25.8,
            pb_ratio: 8.9
        },
        {
            code: "300750",
            name: "宁德时代",
            market: "SZ",
            industry: "新能源",
            sector: "科技",
            market_cap: 1100000000000,
            pe_ratio: 32.1,
            pb_ratio: 6.8
        }
    ];
}

// 读取文件内容
function readFileAsText(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = e => resolve(e.target.result);
        reader.onerror = e => reject(e);
        reader.readAsText(file, 'UTF-8');
    });
}

// 解析CSV内容
function parseCsvContent(csvContent) {
    const lines = csvContent.split('\n').filter(line => line.trim());
    const stocks = [];
    
    // 跳过标题行
    for (let i = 1; i < lines.length; i++) {
        const fields = lines[i].split(',').map(field => field.trim());
        
        if (fields.length >= 3) { // 至少需要代码、名称、市场
            const stock = {
                code: fields[0],
                name: fields[1],
                market: fields[2],
                industry: fields[3] || '',
                sector: fields[4] || '',
                market_cap: fields[5] ? parseFloat(fields[5]) : 0,
                pe_ratio: fields[6] ? parseFloat(fields[6]) : 0,
                pb_ratio: fields[7] ? parseFloat(fields[7]) : 0
            };
            
            if (stock.code && stock.name && stock.market) {
                stocks.push(stock);
            }
        }
    }
    
    return stocks;
}

// 显示导入结果
function showImportResult(result) {
    const resultDiv = document.getElementById('import-result');
    const summaryDiv = document.getElementById('import-summary');
    const errorsDiv = document.getElementById('import-errors');
    
    // 统计信息
    summaryDiv.innerHTML = `
        <div class="result-stats">
            <div class="stat-item">
                <span class="stat-label">总数量:</span>
                <span class="stat-value">${result.total_count}</span>
            </div>
            <div class="stat-item">
                <span class="stat-label">成功:</span>
                <span class="stat-value success">${result.success_count}</span>
            </div>
            <div class="stat-item">
                <span class="stat-label">失败:</span>
                <span class="stat-value error">${result.failed_count}</span>
            </div>
            <div class="stat-item">
                <span class="stat-label">跳过:</span>
                <span class="stat-value warning">${result.skipped_count}</span>
            </div>
            <div class="stat-item">
                <span class="stat-label">更新:</span>
                <span class="stat-value info">${result.updated_count}</span>
            </div>
        </div>
    `;
    
    // 错误信息
    if (result.errors && result.errors.length > 0) {
        errorsDiv.innerHTML = `
            <h5>错误信息:</h5>
            <ul class="error-list">
                ${result.errors.map(error => `<li>${error}</li>`).join('')}
            </ul>
        `;
    } else {
        errorsDiv.innerHTML = '';
    }
    
    resultDiv.style.display = 'block';
    
    // 如果有成功导入的数据，刷新列表
    if (result.success_count > 0 || result.updated_count > 0) {
        setTimeout(() => {
            loadStocksList();
        }, 2000);
    }
}

// 执行登录
async function performLogin() {
    const form = document.getElementById('login-form');
    const formData = new FormData(form);
    const loginData = Object.fromEntries(formData);
    
    try {
        const result = await login(loginData.username, loginData.password);
        setToken(result.data.access_token);
        document.getElementById('loginModal').style.display = 'none';
        initializeApp();
        showAlert('登录成功', 'success');
    } catch (error) {
        showAlert('登录失败: ' + error.message, 'error');
    }
}

// 退出登录
function logout() {
    removeToken();
    location.reload();
}

// 显示警告消息
function showAlert(message, type = 'success') {
    const alertClass = type === 'success' ? 'alert-success' : 'alert-error';
    const alertHtml = `<div class="alert ${alertClass}">${message}</div>`;
    
    // 在当前页面顶部显示
    const currentPage = document.querySelector('.page.active');
    if (currentPage) {
        currentPage.insertAdjacentHTML('afterbegin', alertHtml);
        
        // 3秒后自动移除
        setTimeout(() => {
            const alert = currentPage.querySelector('.alert');
            if (alert) alert.remove();
        }, 3000);
    }
}

// 保存风险设置
function saveRiskSettings() {
    showAlert('风险设置保存成功', 'success');
}

// 股票搜索功能
async function searchStocks() {
    const keyword = document.getElementById('stock-search')?.value || '';
    const market = document.getElementById('market-filter')?.value || '';
    const industry = document.getElementById('industry-filter')?.value || '';
    const status = document.getElementById('status-filter')?.value || '';
    
    // 高级筛选条件
    const minMarketCap = document.getElementById('min-market-cap')?.value || '';
    const maxMarketCap = document.getElementById('max-market-cap')?.value || '';
    const minPeRatio = document.getElementById('min-pe-ratio')?.value || '';
    const maxPeRatio = document.getElementById('max-pe-ratio')?.value || '';
    const sortBy = document.getElementById('sort-by')?.value || 'market_cap';
    const sortOrder = document.getElementById('sort-order')?.value || 'desc';
    
    const params = {
        page: 1, // 搜索时重置为第一页
        limit: 20,
        sort_by: sortBy,
        sort_order: sortOrder
    };
    
    if (keyword) params.keyword = keyword;
    if (market) params.market = market;
    if (industry) params.industry = industry;
    if (status !== '') params.is_active = status === 'true';
    if (minMarketCap) params.min_market_cap = parseFloat(minMarketCap) * 100000000; // 转换为元
    if (maxMarketCap) params.max_market_cap = parseFloat(maxMarketCap) * 100000000;
    if (minPeRatio) params.min_pe_ratio = parseFloat(minPeRatio);
    if (maxPeRatio) params.max_pe_ratio = parseFloat(maxPeRatio);
    
    await loadStocksList(params);
}

// 重置筛选条件
function resetFilters() {
    document.getElementById('stock-search').value = '';
    document.getElementById('market-filter').value = '';
    document.getElementById('industry-filter').value = '';
    document.getElementById('status-filter').value = '';
    
    // 重置高级筛选
    const advancedInputs = ['min-market-cap', 'max-market-cap', 'min-pe-ratio', 'max-pe-ratio'];
    advancedInputs.forEach(id => {
        const element = document.getElementById(id);
        if (element) element.value = '';
    });
    
    document.getElementById('sort-by').value = 'market_cap';
    document.getElementById('sort-order').value = 'desc';
    
    loadStocksList();
}

// 切换高级筛选
function toggleAdvancedFilters() {
    const advancedFilters = document.getElementById('advanced-filters');
    if (advancedFilters.style.display === 'none') {
        advancedFilters.style.display = 'flex';
    } else {
        advancedFilters.style.display = 'none';
    }
}

// 全选/取消全选
function toggleSelectAll() {
    const selectAll = document.getElementById('select-all');
    const checkboxes = document.querySelectorAll('.stock-checkbox');
    checkboxes.forEach(cb => cb.checked = selectAll.checked);
}

// 批量更新状态
async function bulkUpdateStatus(isActive) {
    const checkedBoxes = document.querySelectorAll('.stock-checkbox:checked');
    if (checkedBoxes.length === 0) {
        showAlert('请至少选择一支股票', 'error');
        return;
    }
    
    const codes = Array.from(checkedBoxes).map(cb => cb.value);
    const action = isActive ? '启用' : '禁用';
    
    if (!confirm(`确定要${action}选中的 ${codes.length} 支股票吗？`)) {
        return;
    }
    
    try {
        await bulkUpdateStockStatus(codes, isActive);
        showAlert(`批量${action}成功`, 'success');
        loadStocksList();
    } catch (error) {
        showAlert(`批量${action}失败: ` + error.message, 'error');
    }
}

// 批量删除股票
async function bulkDeleteStocks() {
    const checkedBoxes = document.querySelectorAll('.stock-checkbox:checked');
    if (checkedBoxes.length === 0) {
        showAlert('请至少选择一支股票', 'error');
        return;
    }
    
    if (!confirm(`确定要删除选中的 ${checkedBoxes.length} 支股票吗？此操作不可恢复！`)) {
        return;
    }
    
    try {
        for (const checkbox of checkedBoxes) {
            const row = checkbox.closest('tr');
            const deleteButton = row.querySelector('.btn-danger');
            if (deleteButton && deleteButton.onclick) {
                const onclickStr = deleteButton.onclick.toString();
                const match = onclickStr.match(/deleteStockData\((\d+)/); 
                if (match) {
                    const stockId = match[1];
                    await deleteStock(stockId);
                }
            }
        }
        showAlert('批量删除成功', 'success');
        loadStocksList();
    } catch (error) {
        showAlert('批量删除失败: ' + error.message, 'error');
    }
}

// 导出股票数据
async function exportStocks() {
    try {
        const result = await getStocks({ limit: 10000 }); // 获取所有数据
        const stocks = result.data?.list || [];
        
        // 创建CSV内容
        const headers = ['股票代码', '股票名称', '市场', '行业', '板块', '市值(亿)', '市盈率', '市净率', '状态'];
        const csvContent = [headers.join(',')];
        
        stocks.forEach(stock => {
            const row = [
                stock.code,
                stock.name,
                stock.market,
                stock.industry || '',
                stock.sector || '',
                stock.market_cap ? (stock.market_cap / 100000000).toFixed(2) : '',
                stock.pe_ratio || '',
                stock.pb_ratio || '',
                stock.is_active ? '有效' : '无效'
            ];
            csvContent.push(row.join(','));
        });
        
        // 下载文件
        const blob = new Blob([csvContent.join('\n')], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', `stocks_${new Date().toISOString().split('T')[0]}.csv`);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        showAlert('数据导出成功', 'success');
    } catch (error) {
        showAlert('导出失败: ' + error.message, 'error');
    }
}

// 同步市场数据
async function syncMarketDataAction() {
    if (!confirm('确定要同步市场数据吗？这可能需要一些时间。')) {
        return;
    }
    
    try {
        await syncMarketData();
        showAlert('市场数据同步成功', 'success');
        loadStocksList();
    } catch (error) {
        showAlert('同步失败: ' + error.message, 'error');
    }
}

// 编辑股票
async function editStock(id) {
    try {
        const result = await getStockById(id);
        const stock = result.data;
        
        // 创建编辑模态框
        const modalsContainer = document.getElementById('modals');
        modalsContainer.innerHTML = `
            <div id="editStockModal" class="modal" style="display: block;">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3>编辑股票</h3>
                        <button class="close" onclick="closeModal('editStockModal')">&times;</button>
                    </div>
                    <form id="edit-stock-form">
                        <input type="hidden" name="id" value="${stock.id}">
                        <div class="form-group">
                            <label>股票代码</label>
                            <input type="text" class="form-control" name="code" value="${stock.code}" readonly>
                        </div>
                        <div class="form-group">
                            <label>股票名称</label>
                            <input type="text" class="form-control" name="name" value="${stock.name}" required>
                        </div>
                        <div class="form-group">
                            <label>市场</label>
                            <select class="form-control" name="market" required>
                                <option value="SH" ${stock.market === 'SH' ? 'selected' : ''}>上海交易所</option>
                                <option value="SZ" ${stock.market === 'SZ' ? 'selected' : ''}>深圳交易所</option>
                                <option value="BJ" ${stock.market === 'BJ' ? 'selected' : ''}>北京交易所</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>行业</label>
                            <input type="text" class="form-control" name="industry" value="${stock.industry || ''}">
                        </div>
                        <div class="form-group">
                            <label>板块</label>
                            <input type="text" class="form-control" name="sector" value="${stock.sector || ''}">
                        </div>
                        <div class="form-group">
                            <label>市值(元)</label>
                            <input type="number" class="form-control" name="market_cap" value="${stock.market_cap || ''}">
                        </div>
                        <div class="form-group">
                            <label>市盈率</label>
                            <input type="number" step="0.01" class="form-control" name="pe_ratio" value="${stock.pe_ratio || ''}">
                        </div>
                        <div class="form-group">
                            <label>市净率</label>
                            <input type="number" step="0.01" class="form-control" name="pb_ratio" value="${stock.pb_ratio || ''}">
                        </div>
                        <div class="form-group">
                            <label>状态</label>
                            <select class="form-control" name="is_active">
                                <option value="true" ${stock.is_active ? 'selected' : ''}>有效</option>
                                <option value="false" ${!stock.is_active ? 'selected' : ''}>无效</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <button type="button" class="btn btn-primary" onclick="updateStockData()">保存</button>
                            <button type="button" class="btn" onclick="closeModal('editStockModal')">取消</button>
                        </div>
                    </form>
                </div>
            </div>
        `;
    } catch (error) {
        showAlert('获取股票信息失败: ' + error.message, 'error');
    }
}

// 更新股票
async function updateStockData() {
    const form = document.getElementById('edit-stock-form');
    const formData = new FormData(form);
    const stockData = Object.fromEntries(formData);
    
    // 处理数据类型转换
    if (stockData.market_cap) stockData.market_cap = parseFloat(stockData.market_cap);
    if (stockData.pe_ratio) stockData.pe_ratio = parseFloat(stockData.pe_ratio);
    if (stockData.pb_ratio) stockData.pb_ratio = parseFloat(stockData.pb_ratio);
    stockData.is_active = stockData.is_active === 'true';
    
    const id = stockData.id;
    delete stockData.id;
    delete stockData.code; // 代码不允许修改
    
    try {
        await updateStock(id, stockData);
        closeModal('editStockModal');
        showAlert('股票更新成功', 'success');
        loadStocksList();
    } catch (error) {
        showAlert('更新失败: ' + error.message, 'error');
    }
}

// 删除股票
async function deleteStockData(id, name) {
    if (!confirm(`确定要删除股票 "${name || id}" 吗？此操作不可恢复！`)) {
        return;
    }
    
    try {
        await deleteStock(id);
        showAlert('股票删除成功', 'success');
        loadStocksList();
    } catch (error) {
        showAlert('删除失败: ' + error.message, 'error');
    }
}

// 其他编辑函数（待实现）
function editPool(id) { console.log('编辑股票池:', id); }
function deletePool(id) { console.log('删除股票池:', id); }
function editTag(id) { console.log('编辑标签:', id); }
function deleteTag(id) { console.log('删除标签:', id); }
function editStrategy(id) { console.log('编辑策略:', id); }
function deleteStrategy(id) { console.log('删除策略:', id); }

// ========== 桌面应用特有功能 ==========

// 初始化桌面应用特有功能
function initDesktopFeatures() {
    console.log('初始化桌面应用特有功能...');
    
    // 添加桌面应用标识
    document.body.classList.add('desktop-app');
    
    // 显示桌面模式提示
    const header = document.querySelector('.header h2');
    if (header) {
        header.innerHTML += ' <span class="app-mode-badge">桌面版</span>';
    }
    
    // 初始化桌面通知
    initDesktopNotifications();
    
    // 监听窗口事件
    setupDesktopWindowEvents();
    
    console.log('桌面应用功能初始化完成');
}

// 初始化桌面通知
function initDesktopNotifications() {
    // 重写 showAlert 函数以支持桌面通知
    const originalShowAlert = window.showAlert;
    window.showAlert = function(message, type = 'info') {
        // 调用原始的 showAlert
        if (originalShowAlert) {
            originalShowAlert(message, type);
        } else {
            console.log(`${type.toUpperCase()}: ${message}`);
        }
        
        // 发送桌面通知
        if (isDesktopApp) {
            const title = type === 'success' ? '操作成功' : 
                         type === 'error' ? '操作失败' : 
                         type === 'warning' ? '警告' : '提示';
            showDesktopNotification(title, message);
        }
    };
}

// 设置桌面窗口事件
function setupDesktopWindowEvents() {
    // 监听快捷键
    document.addEventListener('keydown', function(event) {
        // Ctrl+R 刷新当前页面数据
        if (event.ctrlKey && event.key === 'r') {
            event.preventDefault();
            refreshCurrentPageData();
        }
        
        // F5 刷新整个应用
        if (event.key === 'F5') {
            event.preventDefault();
            location.reload();
        }
        
        // Ctrl+N 快速添加
        if (event.ctrlKey && event.key === 'n') {
            event.preventDefault();
            quickAdd();
        }
    });
}

// 刷新当前页面数据
function refreshCurrentPageData() {
    const activePage = document.querySelector('.page.active');
    if (activePage) {
        const pageId = activePage.id;
        console.log('刷新页面数据:', pageId);
        loadPageData(pageId);
        showDesktopNotification('数据刷新', `${pageId} 页面数据已刷新`);
    }
}

// 快速添加功能
function quickAdd() {
    const activePage = document.querySelector('.page.active');
    if (activePage) {
        const pageId = activePage.id;
        switch(pageId) {
            case 'stocks':
                openModal('stockModal');
                break;
            case 'pools':
                openModal('poolModal');
                break;
            case 'tags':
                openModal('tagModal');
                break;
            case 'strategies':
                openModal('strategyModal');
                break;
            default:
                showDesktopNotification('快速添加', '当前页面不支持快速添加功能');
        }
    }
}

// 桌面版本的文件选择优化
function enhancedFileSelect() {
    // 这里可以添加桌面版本特有的文件选择逻辑
    // 比如拖拽文件支持等
    console.log('桌面版文件选择功能');
}

// 获取桌面应用状态
function getDesktopAppStatus() {
    if (!isDesktopApp) {
        return null;
    }
    
    return {
        mode: 'desktop',
        platform: navigator.platform,
        userAgent: navigator.userAgent,
        language: navigator.language,
        online: navigator.onLine
    };
}

// 桌面应用调试信息
function showDesktopDebugInfo() {
    if (isDesktopApp) {
        console.log('=== 桌面应用调试信息 ===');
        console.log('运行模式:', appMode);
        console.log('Wails API 可用:', !!wailsAPI);
        console.log('应用状态:', getDesktopAppStatus());
        console.log('========================');
    }
}

// 在控制台执行调试信息
if (isDesktopApp) {
    setTimeout(showDesktopDebugInfo, 1000);
}